import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @author lzm
 * @date 2025/2/25 20:52
 * @description 线程不安全的单例模式
 */
public class Sun {

    private static Sun instance;

    /**
     * 私有构造器，禁止外部实例化
     */
    private Sun() {
    }

    public static Sun getInstance() {
        // 如果对象还未创建，则创建一个新的对象
        if (instance == null) {
            try {
                // 模拟初始化对象的准备时间
                TimeUnit.MILLISECONDS.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            instance = new Sun();
        }
        return instance;
    }

    public static void main(String[] args) throws InterruptedException {
        // 创建10个线程，每个线程都获取sun的实例，
        ArrayList<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                Sun sun = Sun.getInstance();
                System.out.println(sun.hashCode());
            });
            threads.add(thread);
        }
        for (Thread thread : threads) {
            thread.start();
        }
        TimeUnit.SECONDS.sleep(1);
    }

}